package com.bocloud.cmp.service.utils;

import java.io.IOException;
import java.net.SocketException;
import java.util.List;
import java.util.Random;

import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import com.bocloud.common.ssh.CommandExcutor;
import com.bocloud.common.ssh.SSH;

public class HostUtil {

	private static final Logger LOGGER = Logger.getLogger(HostUtil.class);
	
	//获取所有主机没有占用的随机端口号
	public static String getFreePort(List<SSH> sshs) {
		String port = "";
		Random random = new Random();
		boolean getResult = false;
		int index = 0;
		while (!getResult) {
			int tip = random.nextInt(1_0000);
			port = (3_0000 + tip) + "";
			for (SSH ssh : sshs) {
				try {
					if (ssh.connect()) {
						String portStatus = CommandExcutor.execute4Result(ssh, ServerCommand.checkPort(port));
						if (StringUtils.hasText(portStatus)) {
							continue;
						} else {
							index ++;
							if (index == sshs.size()) {
								getResult = true;
							}
						}
					} else {
						break;
					}
				} catch (SocketException e) {
					LOGGER.error("SocketException get ssh failed", e);
					return "exception";
				} catch (IOException e) {
					LOGGER.error("IOException get ssh failed", e);
					return "exception";
				}

				try {
					/** 休眠50毫秒 */
					Thread.sleep(50);
				} catch (InterruptedException e) {
					LOGGER.error("InterruptedException sleep failed", e);
					return "exception";
				}
			}
		}

		return port;
	}
}
